const http = require('http')
const parse = require('url').parse
const join = require('path').join
const fs = require('fs')
const root = __dirname

const server = http.createServer((req, res) => {
  const url = parse(req.url)
  const path = join(root, url.pathname)
  console.log('path:', path)

  fs.stat(path, (err, stat) => {
    if (err) {
      if (err.code === 'ENOENT') {
        res.statusCode = 404
        res.end('Not Found')
      } else {
        res.statusCode = 500
        res.end('Internal Server Error\n' + err)
      }
      return
    }

    res.setHeader('Content-Length', stat.size)
    const stream = fs.createReadStream(path)
    // stream.on('data', chunk => {
    //   res.write(chunk)
    // })
    // stream.on('end', () => {
    //   res.end()
    // })
    stream.pipe(res)
    stream.on('error', err => {
      console.error(err)
      res.statusCode = 500
      res.end('Internal Server Error\n' + err)
    })
  })


})
server.listen(3000, () => {
  console.log('HTTP server running in port: http://localhost:3000')
})
